<?php

declare(strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;
use think\facade\Event;

class Bonus extends Base
{

    protected $name = 'bonus';
    /**
     * 分红
     */
    public static function directorBonus()
    {
        try {
            $user = User::where('team_id', 9)->select();
            $info = parent::whereDay('create_time', 'yesterday')->where('status', 0)->find();
            $toal = 0;
            if (!empty($info)) {
                $info->price = count($user) > 0 ? round($info['bonus'] / count($user), 2) : 0;
                $info->num = count($user);
                $info->status = 1;
                $info->save();
                if (count($user) > 0) {
                    foreach ($user as $v) {
                        $data['uid'] = $v['id'];
                        $data['bonus_id'] = $info['id'];
                        UserBonus::create($data);
                        $money = Relation::getBurn($info->price, $v['id']);
                        if ($money > 0) {
                            Target::Account()->basics($v['id'], 'bonus_2', $money, '董事分红释放', '-')
                                ->createNormal();
                            Target::Account()->basics($v['id'], 'bonus_3', $money, '董事分红', '+')
                                ->createBonus(0, 5);
                            $toal += $money;
                        }
                    }
                }
                if ($toal > 0) {
                    Event::trigger('Statistics', ['key' => 'expend', 'value' => $toal]);
                }
                return ['code' => 1, 'msg' => '分红成功！参与分红人数为' . count($user) . '人，分红总金额为' . $info['bonus'] . '元！'];
            } else {
                return ['code' => -1, 'msg' => '分红已进行过，请勿重复操作！'];
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
